package com.atguigu.day02;

import com.atguigu.utils.IntSource;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

public class Example8 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .addSource(new IntSource())
                .keyBy(r -> 1)
                .process(new IntStatistic())
                .print();

        env.execute();
    }

    public static class IntStatistic extends KeyedProcessFunction<Integer, Integer, Statistics> {
        private ValueState<Statistics> accumulator;

        // 用来保存定时器的时间戳
        private ValueState<Long> timerTs;

        @Override
        public void open(Configuration parameters) throws Exception {
            accumulator = getRuntimeContext().getState(new ValueStateDescriptor<Statistics>("acc", Types.POJO(Statistics.class)));
            timerTs = getRuntimeContext().getState(new ValueStateDescriptor<Long>("timer-ts", Types.LONG));
        }

        @Override
        public void processElement(Integer value, Context ctx, Collector<Statistics> out) throws Exception {
            if (accumulator.value() == null) {
                // 第一条数据到达
                accumulator.update(
                        new Statistics(
                                value,
                                1,
                                value,
                                value,
                                value
                        )
                );
            } else {
                // 取出累加器
                Statistics tmp = accumulator.value();
                // 做累加操作并更新累加器
                accumulator.update(
                        new Statistics(
                                tmp.sum + value,
                                tmp.count + 1,
                                (tmp.sum + value) / (tmp.count + 1),
                                Math.min(tmp.min, value),
                                Math.max(tmp.max, value)
                        )
                );
            }

            if (timerTs.value() == null) {
                // 说明不存在定时器
                long tenSecLater = ctx.timerService().currentProcessingTime() + 10 * 1000L;
                ctx.timerService().registerProcessingTimeTimer(tenSecLater);
                // 将定时器的时间戳保存在状态变量里面
                timerTs.update(tenSecLater);
            }
        }

        // 定时器用来向下游发送统计数据
        @Override
        public void onTimer(long timestamp, OnTimerContext ctx, Collector<Statistics> out) throws Exception {
            if (accumulator.value() != null) out.collect(accumulator.value());
            // 清空状态变量，将timerTs.value = null
            timerTs.clear();
        }
    }

    public static class Statistics {
        public Integer sum;
        public Integer count;
        public Integer avg;
        public Integer min;
        public Integer max;

        public Statistics() {
        }

        public Statistics(Integer sum, Integer count, Integer avg, Integer min, Integer max) {
            this.sum = sum;
            this.count = count;
            this.avg = avg;
            this.min = min;
            this.max = max;
        }

        @Override
        public String toString() {
            return "Statistics{" +
                    "sum=" + sum +
                    ", count=" + count +
                    ", avg=" + avg +
                    ", min=" + min +
                    ", max=" + max +
                    '}';
        }
    }
}
